//
//  LoginAndRegistViewController.m
//  hello mui
//
//  Created by zhangtao on 15/9/17.
//  Copyright (c) 2015年 zt.td. All rights reserved.
//

#import "LoginAndRegistViewController.h"
#import "RegistViewController.h"
#import "MainTabBarViewController.h"
#import "ForgetPsdViewController.h"
#import "WXApiRequestHandler.h"
#import "AppDelegate.h"
//#import "w"
//#import <CommonCrypto/CommonDigest.h>
//#import "WXApiRequestHandler.h"

//#import "Constant.h"
//#import "WXApiRequestHandler.h"
@interface LoginAndRegistViewController ()<UIWebViewDelegate>
@property (strong, nonatomic) IBOutlet UIButton *loginBtn;
@property (strong, nonatomic) IBOutlet UIView *psdView;

@property (strong, nonatomic) IBOutlet UIView *phoneNumView;
@property (weak, nonatomic) IBOutlet UITextField *phoneNum;
@property (strong, nonatomic) IBOutlet UITextField *psdText;

@property(nonatomic,strong)NSArray *tencentArray;

@property(nonatomic,strong)NSString *openid;
@property(nonatomic,strong)NSString *access_token;
@end

@implementation LoginAndRegistViewController
- (IBAction)forgetPsdBtn:(id)sender {
    ForgetPsdViewController *forget = [self.storyboard instantiateViewControllerWithIdentifier:@"psdOne"];
    [self presentViewController:forget animated:NO completion:nil];
}

- (IBAction)back:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    

    
    [super viewDidLoad];
    [self.view setTranslatesAutoresizingMaskIntoConstraints:YES];

    
    _userHeaderImg.layer.cornerRadius = _userHeaderImg.frame.size.width/2;
    
    self.navigationController.navigationBar.hidden = YES;
    
    [self initControls];
    _phoneNum.placeholder = @"请输入手机号";
    _psdText.placeholder = @"请输入密码" ;
    [_phoneNum setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

    [_psdText setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    _psdText.secureTextEntry = YES;
    
//    _psdText.autocorrectionType = UITextAutocorrectionTypeNo;
//    _psdText.autocapitalizationType = UITextAutocapitalizationTypeNone;
       // Do any additional setup after loading the view.
}

-(void)initControls{
    _loginBtn.layer.cornerRadius =
    _psdView.layer.cornerRadius =
    _phoneNumView.layer.cornerRadius =  27;
//    _psdView.bounds.size.height/2;
    
    _psdView.layer.borderWidth =
    _phoneNumView.layer.borderWidth = 1;
    
    _psdView.layer.borderColor      =
    _phoneNumView.layer.borderColor =
    [[UIColor whiteColor]CGColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)toRegist:(id)sender {
    RegistViewController *regist = [self.storyboard instantiateViewControllerWithIdentifier:@"regist"];
    [self presentViewController:regist animated:NO completion:nil];
}

//点击凤凰登陆，直接进入
- (IBAction)testTabBar:(id)sender {
    WebViewController *web = [self.storyboard instantiateViewControllerWithIdentifier:@"web"];
    [self presentViewController:web animated:NO completion:nil];
    
//    const char *cstr = [@"aaa" UTF8String];
//    unsigned char result[8];
//    CC_MD5(cstr,strlen(cstr),result);
//    
//    NSString *md5 =  [NSString stringWithFormat:
//            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
//            result[0], result[1], result[2], result[3],
//            result[4], result[5], result[6], result[7],
//            result[8], result[9], result[10], result[11],
//            result[12], result[13], result[14], result[15]
//            ];
//    NSLog(@"~~~~~~%@",md5);
    
//    MainTabBarViewController *main = [self.storyboard instantiateViewControllerWithIdentifier:@"main"];
//    [self presentViewController:main
//                       animated:YES completion:nil];
    
    
//    UIViewController *vc = [[UIViewController alloc]init];
//    UIWebView *web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0,self.view.frame.size.width, self.view.frame.size.height)];
//    [vc.view addSubview:web];
//        [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.neohoo.com/1.html"]]];
    
}


- (IBAction)login:(id)sender {
    if (_phoneNum.text.length!=11||_psdText.text.length==0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入正确的手机号码或密码" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }else{
        
        //登陆
    NSString *path = @"login/login";
        NSString *phoneNum = _phoneNum.text;
        NSUSER_DEF_NORSET(phoneNum, @"LOGINPHONE");
//    NSDictionary *dic = @{@"username":phoneNum,@"password":_psdText.text};
        NSMutableDictionary *dics = [NSMutableDictionary dictionaryWithObjectsAndKeys:phoneNum,@"username",_psdText.text,@"password", nil];
        
        
        [[HttpConnctionManager sharedInstance]requestParam:MD5 andUrl:path andSuccessedBlock:^(NSDictionary *succeedResult) {
            NSLog(@"%@",MD5);
       NSLog(@"success:%@",succeedResult);
       NSString *recode =[NSString stringWithFormat:@"%@", [succeedResult valueForKey:@"resCode"]];
       
       if ([recode isEqualToString:@"0"]) {   //login-->>success
           NSUSER_DEF_NORSET(SELF_LOGIN, SHARE);
           
           NSString *userid =[NSString stringWithFormat:@"%@", [[succeedResult valueForKey:@"resData"]valueForKey:@"userId"]];
           NSUSER_DEF_NORSET(userid, @"USERID");
           
           NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"address"], @"ADDRESS");
           
           NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"email"], @"EMAIL");
           
           NSString *str = [NSString stringWithFormat:@"%@", [[succeedResult valueForKey:@"resData"]stringWithFilted:@"gener"]];
           if (str && [str isEqualToString:@"0"]) {
               NSUSER_DEF_NORSET(@"男", @"GENER");
           }else if(str && [str isEqualToString:@"1"]){
               NSUSER_DEF_NORSET(@"女", @"GENER");
           }
           
           NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"headImg"], @"HEADIMG");
           
           NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"nickName"], @"NICKNAME");
           
            NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"operatorId"], @"OPERATORID");
           
            NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"phone"], @"PHONE");
           
            NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"state"], @"STATE");
           
           
            NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"trueName"], @"TRUENAME");
           
           
            NSUSER_DEF_NORSET([[succeedResult valueForKey:@"resData"]stringWithFilted:@"userName"], @"USERNAME");
           MainTabBarViewController *main = [self.storyboard instantiateViewControllerWithIdentifier:@"main"];
           [self presentViewController:main
                              animated:YES completion:nil];
//           [ToolObjc loginLoginIn:userid];
           [ToolObjc loginOUtLoginIn:userid];

//           [self loginSuccessed:userid];
       }else if([recode isEqualToString:@"1"]){    //login--->faile-->>注册
           RegistViewController *regist = [self.storyboard instantiateViewControllerWithIdentifier:@"regist"];
           [self.navigationController pushViewController:regist animated:YES];
                 }
   } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
       //
       NSLog(@"error网络连接错误:%@",error);
   }];
    }
    
}


//*QQ*/
- (IBAction)tencentLogin:(id)sender {
    
    NSUSER_DEF_NORSET(TENCENT_LOGIN, SHARE);

    NSArray* permissions = [NSArray arrayWithObjects:
                            kOPEN_PERMISSION_GET_USER_INFO,
//                            kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
//                            kOPEN_PERMISSION_ADD_ALBUM,
//                            kOPEN_PERMISSION_ADD_IDOL,
//                            kOPEN_PERMISSION_ADD_ONE_BLOG,
//                            kOPEN_PERMISSION_ADD_PIC_T,
//                            kOPEN_PERMISSION_ADD_SHARE,
//                            kOPEN_PERMISSION_ADD_TOPIC,
//                            kOPEN_PERMISSION_CHECK_PAGE_FANS,
//                            kOPEN_PERMISSION_DEL_IDOL,
//                            kOPEN_PERMISSION_DEL_T,
//                            kOPEN_PERMISSION_GET_FANSLIST,
//                            kOPEN_PERMISSION_GET_IDOLLIST,
//                            kOPEN_PERMISSION_GET_INFO,
//                            kOPEN_PERMISSION_GET_OTHER_INFO,
//                            kOPEN_PERMISSION_GET_REPOST_LIST,
//                            kOPEN_PERMISSION_LIST_ALBUM,
//                            kOPEN_PERMISSION_UPLOAD_PIC,
//                            kOPEN_PERMISSION_GET_VIP_INFO,
//                            kOPEN_PERMISSION_GET_VIP_RICH_INFO,
//                            kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
//                            kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                            nil];

    tencentOAuth = [[TencentOAuth alloc]initWithAppId:TencentAppid andDelegate:self];
//    _tencentArray = [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo",@"add_t", nil];
    [tencentOAuth authorize:permissions inSafari:NO];
}

-(void)tencentDidLogin{
    if (tencentOAuth.accessToken && 0!=[tencentOAuth.accessToken length]) {
        [[NSUserDefaults standardUserDefaults]setValue:tencentOAuth.accessToken forKey:@"TencentAccessToken"];
        
      [tencentOAuth getUserInfo];
      
        [[NSUserDefaults standardUserDefaults]setValue:tencentOAuth.openId forKey:@"OPENID"];
        NSLog(@"~!~!~!!~~!%@",NSUSER_DEF(@"TencentOpenId"));
        [[NSUserDefaults standardUserDefaults]setValue:@"Tencent" forKey:@"SHARE"];
        [ToolObjc thredLogin:@"QQ"];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"登陆失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

//非网络导致失败
-(void)tencentDidNotLogin:(BOOL)cancelled{
    NSLog(@"333333333333");

}
//无网络连接
-(void)tencentDidNotNetWork{
    NSLog(@"无网络。。。。。。。。。。");
}

-(void)getUserInfoResponse:(APIResponse *)response{
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:nil];
    NSDictionary *dic = [response valueForKey:@"jsonResponse"];
   
    
    NSUSER_DEF_SET(@"figureurl_1", @"USERHEADER");
    NSUSER_DEF_SET(@"nickname", @"NICKNAME");
    NSUSER_DEF_SET(@"gender", @"GENDER");
    
    MainTabBarViewController *main = [self.storyboard instantiateViewControllerWithIdentifier:@"main"];
    [self presentViewController:main animated:NO completion:nil];
}



#pragma mark message
-(void)loginSuccessed:(NSString *)userid
{
//    dispatch_async(dispatch_get_global_queue(0,0 ), ^{
//        [ToolObjc loginLoginIn:userid];
//
//    });dispatch_async(dispatch_get_main_queue(), ^{
    
    
//    });

    
//    } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
//        
//    }];
    
    
   
}

- (void)loginFailed
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"登录失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
}





/**微信*/

- (IBAction)WXLogin:(id)sender {
    
    NSUSER_DEF_NORSET(WECHAT_LOGIN, SHARE);

    [self sendAuthRequest];
}

-(void)sendAuthRequest{
    NSLog(@"333333333");
    
    MainTabBarViewController *main = [self.storyboard instantiateViewControllerWithIdentifier:@"main"];
    [self presentViewController:main animated:NO completion:nil];
    [ToolObjc showMessage:@"登陆成功"];
    [main sendAuthRequest];
//    [WXApiRequestHandler sendAuthRequestScope: Scope
//                                        State:@"state"
//                                       OpenID:AppID
//                             InViewController:self];
}




- (void)getUserInfo {
    NSLog(@"1111111111111");
    NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", self.access_token, self.openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"openid = %@", [dic objectForKey:@"openid"]);
                NSLog(@"nickname = %@", [dic objectForKey:@"nickname"]);
                NSLog(@"sex = %@", [dic objectForKey:@"sex"]);
                NSLog(@"country = %@", [dic objectForKey:@"country"]);
                NSLog(@"province = %@", [dic objectForKey:@"province"]);
                NSLog(@"city = %@", [dic objectForKey:@"city"]);
                NSLog(@"headimgurl = %@", [dic objectForKey:@"headimgurl"]);
                NSLog(@"unionid = %@", [dic objectForKey:@"unionid"]);
                NSLog(@"privilege = %@", [dic objectForKey:@"privilege"]);
                
                AppDelegate *appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                appdelegate.headimgurl = [dic objectForKey:@"headimgurl"]; // 传递头像地址
                appdelegate.nickname = [dic objectForKey:@"nickname"]; // 传递昵称
                //                NSLog(@"appdelegate.headimgurl == %@", appdelegate.headimgurl); // 测试
                //                NSLog(@"appdelegate.nickname == %@", appdelegate.nickname);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Note" object:nil]; // 发送通知
//                MainTabBarViewController *main = [self.storyboard instantiateViewControllerWithIdentifier:@"main"];
//                [self presentViewController:main animated:NO completion:nil];
            
            }
        });
    });
}




-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_phoneNum resignFirstResponder];
    [_psdText resignFirstResponder];
}





@end
